package mysqlGORM

import (
	"fmt"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	"rpcSrv/configs"
	"rpcSrv/utils"
)

type dbInfo struct {
	db  *gorm.DB
	err error
}

var (
	dbMap = make(map[string]dbInfo)
)

func GetMysqlDB() (*gorm.DB, error) {
	db_info := configs.GetMysqlConf()
	return GetDB(db_info)
}

func GetDB(db_info configs.MysqlConf) (*gorm.DB, error) {
	// map[dbname] return
	db, ok := dbMap[db_info.DB]
	if !ok {
		//create
		url := fmt.Sprintf("%v:%v@tcp(%v:%v)/%v?charset=utf8&parseTime=true&loc=Local",
			db_info.Username, db_info.Password, db_info.Ip, db_info.Port, db_info.DB)
		DB, err := gorm.Open("mysql", url)
		if utils.CheckErr(err) {
			dbMap[fmt.Sprintf("%v", db_info.DB)] = dbInfo{db: nil, err: err}
			return nil, err
		}
		DB.LogMode(true)
		DB.DB().SetMaxIdleConns(2000)
		DB.DB().SetMaxOpenConns(1000)
		dbMap[fmt.Sprintf("%v", db_info.DB)] = dbInfo{db: DB, err: nil}
		return DB, nil
	}
	return db.db, db.err
}
